package apbms

class SocioController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    
    static allowedExt = ["jpeg", "png", "gif", "bmp"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [socioInstanceList: Socio.list(params), socioInstanceTotal: Socio.count()]
    }

    def create = {
        def socioInstance = new Socio()
        def enderInstance = new Endereco()
        socioInstance.endereco = enderInstance
        socioInstance.properties = params
        return [socioInstance: socioInstance]
    }
    
    def confere = {
        def file = request.getFile("foto3x4")
        if(file.empty){
            return 1
        }
        def tipo = params.foto3x4.contentType
        def trueExt 
        for (ext in allowedExt){
            if( tipo.toLowerCase().contains(ext)){
                trueExt = ext
            }
        }
        if(!trueExt){
            flash.message = "Não foi possível carregar da foto. Extensões permitidas: jpg, bmp, gif, png"
            return null;
        }
        def tamanho = params.foto3x4.size
        if(tamanho > (1024*1024) ){
            flash.message = "Não foi possível carregar da foto. Tamanho máximo permitido: 1MB"
            return null;
        }
        return 1
    }
    
    def upload = { socioInstance ->        
        def file = request.getFile("foto3x4")
        if(!file.empty){
            file.transferTo(new File(servletContext.getRealPath("images/fotos/${socioInstance.id.toString()}")))
        }else{
            flash.message = "Não foi possível transferir o arquivo da foto."
        }
    }

    def save = {
        def socioInstance = new Socio(params)
        def enderInstace = new Endereco(params)
        enderInstace.morador = socioInstance
        socioInstance.endereco = enderInstace
        if(!confere){
            render(view: "create", model: [socioInstance: socioInstance])
        }
        def nomeOriginal = params.foto3x4.originalFilename
        socioInstance.foto3x4 = nomeOriginal
        if (socioInstance.save(flush: true)) {
            enderInstace.save(flush: true)
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'socio.label', default: 'Socio'), socioInstance.id])}"
            upload(socioInstance)
            redirect(action: "show", id: socioInstance.id)
        }
        else {
            render(view: "create", model: [socioInstance: socioInstance, enderInstace: enderInstace ])
        }
    }

    def show = {
        def socioInstance = Socio.get(params.id)
        if (!socioInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'socio.label', default: 'Socio'), params.id])}"
            redirect(action: "list")
        }
        else {
            [socioInstance: socioInstance]
        }
    }

    def edit = {
        def socioInstance = Socio.get(params.id)
        def enderInstance = socioInstance.endereco
        if (!socioInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'socio.label', default: 'Socio'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [socioInstance: socioInstance]
        }
    }

    def update = {
        def socioInstance = Socio.get(params.id)
        if (socioInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (socioInstance.version > version) {
                    
                    socioInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'socio.label', default: 'Socio')] as Object[], "Another user has updated this Socio while you were editing")
                    render(view: "edit", model: [socioInstance: socioInstance])
                    return
                }
            }
            socioInstance.properties = params
            socioInstance.foto3x4 = socioInstance.id.toString()
            def enderInstance = socioInstance.endereco
            enderInstance.properties = params
            if (!socioInstance.hasErrors() && socioInstance.save(flush: true)) {
                enderInstance.save(flush: true)
                if(confere){
                    upload(socioInstance)
                }
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'socio.label', default: 'Socio'), socioInstance.id])}"
                redirect(action: "show", id: socioInstance.id)
            }
            else {
                render(view: "edit", model: [socioInstance: socioInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'socio.label', default: 'Socio'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        if(session.usuario.grupo.equalsIgnoreCase("Visualizador")){
            redirect(action: "show", id: params.id)
        }else{
            def socioInstance = Socio.get(params.id)
            if (socioInstance) {
                def file = new File(servletContext.getRealPath("images/fotos/${socioInstance.id.toString()}"))
                try {
                    socioInstance.delete(flush: true)
                    file.delete()
                    flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'socio.label', default: 'Socio'), params.id])}"
                    redirect(action: "list")
                }
                catch (org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'socio.label', default: 'Socio'), params.id])}"
                    redirect(action: "show", id: params.id)
                }
            }
            else {
                flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'socio.label', default: 'Socio'), params.id])}"
                redirect(action: "list")
            }
        }
    }
    
    def pesquisa = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        def campoDePesquisa = params.campo
        def socioInstanceList = new ArrayList()
        
        [socioInstanceList: socioInstanceList, socioInstanceTotal: socioInstanceList.size()]
    }
    
    def encontrar = {
        def campoDePesquisa = params.campo
        def socioInstanceList
        if(campoDePesquisa){
            def query = Socio.createCriteria()
            socioInstanceList = query {
                or{
                    like("nome", '%' + campoDePesquisa + '%')
                    like("cpf", '%' + campoDePesquisa + '%')
                    like("nomeMae", '%' + campoDePesquisa + '%')
                    like("nomeDeGuerra", '%' + campoDePesquisa + '%')
                    like("matricula", '%' + campoDePesquisa + '%')
                    like("numeroGuerra", '%' + campoDePesquisa + '%')
                }
            }
        }else{
            socioInstanceList = new ArrayList()
        }
        render(view:'pesquisa', model:[ socioInstanceList: socioInstanceList, socioInstanceTotal: socioInstanceList.size() ])
    }
}
